package zhaoq_hero.mymv;


import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.hardware.Camera;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;

import zhaoq_hero.mymv.utils.FileUtils;
import zhaoq_hero.mymv.utils.SecondActivity;

public class MainActivity extends Activity implements SurfaceHolder.Callback {

    private File myRecVideoFile;
    private SurfaceView mSurfaceView;
    private SurfaceHolder mSurfaceHolder;
    private TextView tvTime;
    private TextView tvSize;
    private Button btnStart;
    private Button btnStop;
    private Button btnCancel;
    private MediaRecorder recorder;
    private Handler handler;
    private Camera camera;
    private boolean recording = false; // 记录是否正在录像,    fasle为未录像, true为正在录像
    private int minute = 0;
    private int second = 0;
    private String time = "";
    private String size = "";
    private String fileName;

    /**
     * 录制过程中,时间变化,大小变化
     */
    private Runnable timeRun = new Runnable() {

        @Override
        public void run() {

            long fileLength = myRecVideoFile.length();

            if (fileLength < 1024 && fileLength > 0) {
                size = String.format("%dB/10M", fileLength);
            } else if (fileLength >= 1024 && fileLength < (1024 * 1024)) {
                fileLength = fileLength / 1024;
                size = String.format("%dK/10M", fileLength);
            } else if (fileLength > (1024 * 1024 * 1024)) {
                fileLength = (fileLength / 1024) / 1024;
                size = String.format("%dM/10M", fileLength);
            }

            second++;

            if (second == 60) {
                minute++;
                second = 0;
            }

            time = String.format("%02d:%02d", minute, second);

            tvSize.setText(size);
            tvTime.setText(time);

            handler.postDelayed(timeRun, 1000);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        mSurfaceView = (SurfaceView) findViewById(R.id.videoView);

        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.addCallback(this);
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        mSurfaceHolder.setKeepScreenOn(true);

        handler = new Handler();

        tvTime = (TextView) findViewById(R.id.tv_video_time);
        tvSize = (TextView) findViewById(R.id.tv_video_size);
        btnStop = (Button) findViewById(R.id.btn_video_stop);
        btnStart = (Button) findViewById(R.id.btn_video_start);
        btnCancel = (Button) findViewById(R.id.btn_video_cancel);

        btnCancel.setOnClickListener(listener);
        btnStart.setOnClickListener(listener);
        btnStop.setOnClickListener(listener);

        // 设置sdcard的路径
        File file = FileUtils.getMediaRecorderFolder(getApplicationContext());
        File targetFile = new File(file, "audio-" + System.currentTimeMillis() + ".mp4");
        fileName = targetFile.getAbsolutePath();

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // 开启相机
        if (camera == null) {
            camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
            try {
                camera.setPreviewDisplay(mSurfaceHolder);
                camera.setDisplayOrientation(90);//设置旋转90度
            } catch (IOException e) {
                e.printStackTrace();
                camera.release();//释放 相机
            }
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        // 开始预览
        camera.startPreview();  //开始预览

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // 关闭预览并释放资源
        if (camera != null) {
            camera.stopPreview();
            camera.release();
            camera = null;
        }

    }

    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_video_stop:
                    if (recorder != null) {

                        releaseMediaRecorder();

                        minute = 0;
                        second = 0;
                        handler.removeCallbacks(timeRun);
                        recording = false;
                    }
                    btnStart.setEnabled(true);
                    break;
                case R.id.btn_video_start:
                    if (recorder != null) {

                        releaseMediaRecorder();

                        minute = 0;
                        second = 0;
                        handler.removeCallbacks(timeRun);
                        recording = false;
                    }

                    recorder();
                    btnStart.setEnabled(false);
                    break;
                case R.id.btn_video_cancel:

                    releaseMediaRecorder();//释放摄像机

                    handler.removeCallbacks(timeRun);
                    minute = 0;
                    second = 0;
                    recording = false;
                    MainActivity.this.finish();
                    break;
            }
        }
    };


    //释放recorder资源
    private void releaseMediaRecorder() {
        if (recorder != null) {
            //  recorder.stop();
            recorder.release();
            recorder = null;
        }
    }

    //开始录像
    public void recorder() {
        if (!recording) {
            try {
                // 关闭预览并释放资源
                if (camera != null) {
                    camera.stopPreview();
                    camera.release();
                    camera = null;
                }
                recorder = new MediaRecorder();
                // 声明视频文件对象
                myRecVideoFile = new File(fileName);
                if ( !myRecVideoFile.exists() ) {
                    myRecVideoFile.getParentFile().mkdirs();
                    myRecVideoFile.createNewFile();
                }

                recorder.reset();
                camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
                // 设置摄像头预览顺时针旋转90度，才能使预览图像显示为正确的，而不是逆时针旋转90度的。
                camera.setDisplayOrientation(90);
                camera.unlock();
                recorder.setCamera(camera); //设置摄像头为相机

                recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);//视频源
                recorder.setAudioSource(MediaRecorder.AudioSource.MIC); // 录音源为麦克风

                recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
                recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
                recorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);

                recorder.setAudioChannels(2);
                recorder.setAudioEncodingBitRate(128 * 1024);
                recorder.setAudioSamplingRate(96000);


                recorder.setOutputFile(myRecVideoFile.getAbsolutePath());
                recorder.setPreviewDisplay(mSurfaceHolder.getSurface()); // 预览
                recorder.setMaxFileSize(10 * 1024 * 1024); //设置视频文件的最大值为10M,单位B

                Toast.makeText(getApplicationContext(), "视频录制中...", Toast.LENGTH_SHORT).show();

                recorder.prepare(); // 准备录像
                recorder.start(); // 开始录像

                handler.post(timeRun); // 调用Runable

                recording = true; // 改变录制状态为正在录制

            } catch (IOException e1) {

                releaseMediaRecorder();

                handler.removeCallbacks(timeRun);
                minute = 0;
                second = 0;

                recording = false;
                btnStart.setEnabled(true);

            } catch (IllegalStateException e) {

                releaseMediaRecorder();
                handler.removeCallbacks(timeRun);
                minute = 0;
                second = 0;
                recording = false;
                btnStart.setEnabled(true);

            }
        } else
            Toast.makeText(getApplicationContext(), "视频录制中...", Toast.LENGTH_SHORT).show();
    }


    public void btnIntenttoVideo(View view) {

        Intent intent = new Intent(this, SecondActivity.class);

        startActivity(intent);

    }
}
